﻿using System;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace DarrenSoft.Core
{
    /// <summary>
    /// 关于字符串的公共方法
    /// </summary>
    public class StringHelper
    {
        #region "截取字符串"
        /// <summary>
        /// 截取字符串
        /// 修改人:YM
        /// </summary>
        /// <param name="str"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string SubString(string SoucreStr, int len)
        {

            string result = SoucreStr;
            if (SoucreStr.Length >= len)
            {
                result = SoucreStr.Substring(0, len);
            }
            return result;
        }
       
        /// <summary>
        /// 从第几位截取几个字符串
        /// </summary>
        /// <param name="str"></param>
        /// <param name="begin"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string SubString(string str, int begin, int length)
        {
            if (str.Length < begin)
            {
                return "";
            }
            if (length >= str.Length - begin)
            {
                length = str.Length - begin;
            }
            return str.Substring(begin, length);
        }

        /// <summary>
        /// 截取字符串并且在尾部添加需要的内容
        /// </summary>
        /// <param name="str"></param>
        /// <param name="length"></param>
        /// <param name="appendCode"></param>
        /// <returns></returns>
        public static string SubStringAndAppend(string str, int length, string appendCode)
        {
            return SubString(str, length) + appendCode;
        }
        /// <summary>
        /// 截取HTML n个字符的数据
        /// </summary>
        /// <param name="htmlString"></param>
        /// <param name="length"></param>
        /// <param name="appendCode"></param>
        /// <returns></returns>
        public static string SubStringHTML(string htmlString, int length, string appendCode)
        {
            MatchCollection matchCollection = null;
            StringBuilder resultString = new StringBuilder();
            int charLength = 0;
            char charTemp;
            bool isHtmlMark = false;
            bool isHtmlCode = false;
            char[] pChars = htmlString.ToCharArray();

            for (int i = 0; i < pChars.Length; i++)
            {
                charTemp = pChars[i];

                if (charTemp.Equals("<"))
                {
                    isHtmlMark = true;
                }
                else if (charTemp.Equals("&"))
                {
                    isHtmlCode = true;
                }
                else if (charTemp.Equals(">") && isHtmlMark)
                {
                    charLength--;
                    isHtmlMark = false;
                }
                else if (charTemp.Equals(";") && isHtmlCode)
                {
                    isHtmlCode = false;
                }

                if (!isHtmlCode && !isHtmlMark)
                {
                    charLength++;
                    if (System.Text.Encoding.Default.GetBytes(charTemp + "").Length > 1)
                    {
                        charLength++;
                    }
                }

                resultString.Append(charTemp);
                if (charLength >= length)
                {
                    break;
                }
            }

            resultString.Append(appendCode);
            //取出截取字符串中的HTML标记
            string temp_result = Regex.Replace(resultString.ToString(), "(>)[^<>]*(<?)", "$1$2", RegexOptions.IgnoreCase);
            //去掉不需要结素标记的HTML标记 
            temp_result = Regex.Replace(temp_result, @"</?(area|base|basefont|body|br|col|colgroup|dd|dt|frame|head|hr|html|img|input|isindex|li|link|meta|option|p|param|tbody|td|tfoot|th|thead|tr)[^<>]*/?>", "", RegexOptions.IgnoreCase);
            //去掉成对的HTML标记 
            temp_result = Regex.Replace(temp_result, @"<([a-zA-Z]+)[^<>]*>(.*?)</\1>", "", RegexOptions.IgnoreCase);
            //用正则表达式取出标记
            matchCollection = Regex.Matches(temp_result, "<([a-zA-Z]+)[^<>]*>");
            ArrayList htmlArray = new ArrayList();
            foreach (Match mt in matchCollection)
            {
                htmlArray.Add(mt.Result("$1"));
            }
            for (int i = htmlArray.Count - 1; i >= 0; i--)
            {
                resultString.Append("</");
                resultString.Append(htmlArray[i]);
                resultString.Append(">");
            }
            return resultString.ToString();
        }

        /// <summary>
        /// 过滤字符
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public static string Filter(string sInput)
        {
            if (sInput == null || sInput == "")
                return null;
            string sInput1 = sInput.ToLower();
            string output = sInput;
            string pattern = @"*|and|exec|insert|select|delete|update|count|master|truncate|declare|char(|mid(|chr(|'";
            if (Regex.Match(sInput1, Regex.Escape(pattern), RegexOptions.IgnoreCase).Success)
            {
                output = output.Replace(sInput, "''");
            }
            else
            {
                output = output.Replace("'", "''");
            }
            return output;
        }
        #endregion

        #region "数据类型转换"

        /// <summary>
        /// 将字符转换成日期类型的数据
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static DateTime StringToDateTime(string str)
        {
            if (ValidateHelper.IsDateTime(str))
            {
                return DateTime.Parse(str);
            }
            else
            {
                return DateTime.Parse("1900-1-1");
            }
        }

        /// <summary>
        /// 将字符串类型数据转换成Int类型数据
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static int StringToInt(string str)
        {
            if (ValidateHelper.IsNumberSign(str))
            {
                return int.Parse(str);
            }
            else
            {
                return 0;
            }
        }

        /// <summary>
        /// 将字符串类型数据转换成Double类型数据
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static double String2Double(string str)
        {
            if (ValidateHelper.IsDecimal(str))
            {
                return double.Parse(str);
            }
            else
            {
                return 0.0;
            }
        }

        /// <summary>
        /// 将任何一个Object类型数据转换成string 类型数据，防止为K的数据时
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToString(object obj)
        {
            if (obj != null)
            {
                return obj.ToString();
            }
            else
            {
                return "";
            }
        }
        #endregion

        #region 处理字符
        /// <summary>
        /// 清除所有脚本
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string InputTexts(string text)
        {
            if (string.IsNullOrEmpty(text))
                return string.Empty;
            text = Regex.Replace(text, "[\\s]{2,}", " ");	//two or more spaces
            text = Regex.Replace(text, "(<[b|B][r|R]/*>)+|(<[p|P](.|\\n)*?>)", "\n");	//<br>
            text = Regex.Replace(text, "(\\s*&[n|N][b|B][s|S][p|P];\\s*)+", " ");	//&nbsp;
            text = Regex.Replace(text, "<(.|\\n)*?>", string.Empty);	//any other tags
            text = text.Replace("'", "''");
            return text;
        }
        #endregion


    }
}
